//
//  MessageVC.m
//  InviteJob
//
//  Created by LangLang on 17/10/25.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MessageVC.h"
#import "MessageSysterCell.h"

@interface MessageVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;

@property (nonatomic, strong) UIButton *navRightButton;

@property (nonatomic, strong) NSMutableArray *dataList;

@property (nonatomic,assign)  NSInteger page;


@property (nonatomic,strong) NSString *perpage;



@end

@implementation MessageVC

-(NSMutableArray *)dataList{
    if (!_dataList) {
        _dataList = @[].mutableCopy;
    }
    return _dataList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    TitleView(@"我的消息");
    
    // right item
    self.navRightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [self.navRightButton setImage:[UIImage imageNamed:@"icon_news_delete"] forState:UIControlStateNormal];
    self.navRightButton.imageEdgeInsets = UIEdgeInsetsMake(0,15, 0, -15);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.navRightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    // 事件绑定
    [self.navRightButton addTarget:self action:@selector(navdeleAction) forControlEvents:UIControlEventTouchUpInside];
    
    _page = 1;
    
    self.perpage = @"10";
    
    [self postData];
    
    [self layoutUI];
}
- (void)navdeleAction {
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"清空消息？"  preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *determineAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
       
        [_dataList removeAllObjects];
        [self.tableView reloadData];
        [self postDataDelType:@"all" andMsgId:@""];
        
    }];
    
    [actionSheetController addAction:determineAction];
    [actionSheetController addAction:cancelAction];
    
    [self presentViewController:actionSheetController animated:YES completion:nil];
}

-(void)layoutUI{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.dataSource   =self;
    _tableView.delegate     =self;
    _tableView.backgroundColor = strColor(@"f6f6f6");
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.tableFooterView = [UIView new];
    _tableView.separatorStyle = UITableViewCellEditingStyleNone;
    _tableView.estimatedRowHeight = 90;
    [self.view addSubview:_tableView];
    
    __unsafe_unretained UITableView *tableView = self.tableView;
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self postData];
    }];
    [tableView.mj_header endRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self postData];
    }];
    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = 30;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0f;
}
-(MessageSysterCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageSysterCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cells"];
    if (!cell) {
        cell=[[MessageSysterCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cells"];
    }
    
    BaseModel *model = _dataList[indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.images.image = [UIImage imageNamed:@"icon_news_remind"];
    cell.labelTitles.text = model.title;
    cell.times.text = model.create_time;
    cell.contents.text = model.content;
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.separatorInset=UIEdgeInsetsZero;
    cell.layoutMargins=UIEdgeInsetsZero;
    cell.preservesSuperviewLayoutMargins=NO;
}

#pragma mark -- 删除 --
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return   UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"删除该消息？"  preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *determineAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        _page = 1;
        
        self.perpage = @"10";
        
        BaseModel *model = self.dataList[indexPath.row];
        
        [self postDataDelType:@"part" andMsgId:model.msg_id];
        
        [self.dataList removeObjectAtIndex:indexPath.row];
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        
    }];
    
    [actionSheetController addAction:determineAction];
    [actionSheetController addAction:cancelAction];
    
    [self presentViewController:actionSheetController animated:YES completion:nil];
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}



#pragma mark -- 数据源 --
-(void)postData{
    isUser
    NSString *strUrl = [NSString stringWithFormat:post_msgList_api];
    
    NSDictionary *dicParameter = @{@"user_id":user.user_id,
                                   @"token":user.token,
                                   @"page":[NSString stringWithFormat:@"%ld",_page],
                                   @"perpage":self.perpage};
    
    [PostNetWorking postNetWorkingStr:strUrl andparameters:dicParameter Success:^(id responseObject) {
        
        [self noData:_page ReqresponseObject:responseObject lists:@"lists" dataArr:self.dataList arrCount:responseObject[@"datas"][@"lists"] withTable:self.tableView];
        
    } failed:^(NSError *error) {
        [self endRefreshing:self.tableView];
    }];
}

// 加载无数据显示和加载数据


-(void)noData:(NSInteger)page ReqresponseObject:(id)responseObject lists:(NSString *)lists dataArr:(NSMutableArray *)dataArr  arrCount:(NSArray *)arrCount withTable:(UITableView *)DefineTableView{
    __unsafe_unretained UITableView *tableView = DefineTableView;
    
    int code = [responseObject[@"code"]intValue];
    
    if (code == 200) {
        if (page==1) {
            if (dataArr.count) {
                [dataArr removeAllObjects];
            }
            self.dataList = [BaseModel parsingDateFromResultDict:responseObject andData:lists];
            
        }else {
            [dataArr addObjectsFromArray:[BaseModel parsingDateFromResultDict:responseObject andData:lists]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (arrCount.count>0) {
                
                [self hideNoDataView];
                if (arrCount.count<10) {
                    tableView.mj_footer.hidden = YES;
                 }else {
                    tableView.mj_footer.hidden = NO;
                }
                
            }else {
                if (arrCount.count<=0) {
                    [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
                }
                [self shopNoDataViewBackgroundColor:[UIColor clearColor] withImage:@"img_home_no_news" withLabelMsg:@"没有任何数据" withButton:@"" isY:0];
                
            }
            [self endRefreshing:self.tableView];
            
        });
    }else{
        dataArr = [NSMutableArray array];
        [self endRefreshing:self.tableView];
    }
    
}

-(void)endRefreshing:(UITableView *)DefineTableView{
    __unsafe_unretained UITableView *tableView = DefineTableView;
     [tableView reloadData];
    [tableView.mj_header endRefreshing];
    [tableView.mj_footer endRefreshing];
   
    
}

#pragma mark -- 删除数据 --

-(void)postDataDelType:(NSString *)type andMsgId:(NSString *)msgId{
    isUser
    NSString *strUrl = [NSString stringWithFormat:post_delMsg_api];
    
    NSDictionary *dicParameter = @{@"user_id":user.user_id,
                                   @"token":user.token,
                                   @"type":type,
                                   @"msg_id":msgId};
    
    [PostNetWorking postNetWorkingStr:strUrl andparameters:dicParameter Success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 200) {
            
            SHuiMBhudTextTimeStr(@"删除成功");
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self postData];
                
            });
        }else{
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
        
    } failed:^(NSError *error) {
        
        SHuiMBhudTextTimeStr(@"网络错误");
    }];
}



@end
